import { PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Divider,
  message,
  Input,
  Popconfirm,
  Select,
  TreeSelect,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import {
  queryRule,
  removeRule,
  enableRule,
  disabledRule,
  resetPassWordRule,
  editRule,
  addStaff,
  queryDepartment,
  queryPosition,
  queryPositionMessage,
  queryRole,
  searchStaff,
  queryGetStore,
} from './service';
import { transTitle } from '@/utils/utils';
import styles from '../../../global.less';
import FormItem from 'antd/lib/form/FormItem';
import Access from '@/components/Access/Access';
import './index.less';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields, actionRef) => {
  const hide = message.loading('正在添加');

  try {
    await addStaff(fields);
    hide();
    message.success('添加成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields, actionRef) => {
  const hide = message.loading('正在配置');
  try {
    fields.status === 1
      ? await enableRule({
          id: fields.id,
          version: fields.version + 1,
        })
      : await disabledRule({
          id: fields.id,
          version: fields.version + 1,
        });
    hide();
    message.success('配置成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试1！');
    return false;
  }
};
const { Option } = Select;

const handleEdit = async (fields, actionRef) => {
  const hide = message.loading('正在配置');
  try {
    await editRule(fields);
    hide();
    message.success('配置成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    console.log(error);
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

const handleUpdatePassWord = async (fields, actionRef) => {
  const hide = message.loading('正在配置');
  try {
    await resetPassWordRule({
      id: fields.id,
      version: fields.version + 1,
    });
    hide();
    message.success('配置成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (fields, actionRef) => {
  const hide = message.loading('正在删除');
  const { id } = fields;
  try {
    const res = await removeRule({ id });
    hide();
    res ? message.success('删除成功，即将刷新') : null;
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [FormValues, setFormValues] = useState({});
  const actionRef = useRef();
  const recordRef = useRef();
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const [count, setCount] = useState({});
  const [storeArr, setStoreArr] = useState([]);
  const [storeValue, setStoreValue] = useState([]);
  const [positionIdArr, setPositionIdArr] = useState([]);
  const [positionValue, setPositionValue] = useState();
  const [roleIdArr, setRoleIdArr] = useState([]);
  const [sotreState, setSotreState] = useState(false);
  const [sendStore, setSendStore] = useState();
  const [handleChildren, setHandleChildren] = useState();
  const [commissionValue, setCommissionValue] = useState([]);
  const [commissionState, setCommissionState] = useState(false);
  const searchMessage = async (fields) => {
    try {
      return await searchStaff(fields)
        .then((res) => {
          if (res.code === 0) {
            return res;
          }
        })
        .catch((err) => {});
    } catch (error) {
      return false;
    }
  };
  const handleGetDepartment = async () => {
    try {
      const { data } = await queryDepartment();
      transTitle(data);
      setMenuValues(data);
    } catch (error) {
      return false;
    }
  };
  const handleGetPosition = async () => {
    try {
      const { data } = await queryPosition();
      transTitle(data);
      setPositionIdArr(data);
    } catch (error) {
      return false;
    }
  };
  const handleGetQueryRole = async () => {
    try {
      const { data } = await queryRole();
      setRoleIdArr(data);
    } catch (error) {
      return false;
    }
  };
  // const handleGetStore = async (state) => {
  //   try {
  //     const { data } = await queryStore();
  //     state ? null : (transTitle(data), (recordRef.current = JSON.parse(JSON.stringify(data))));
  //     setStoreArr(data);
  //     console.log(recordRef);
  //   } catch (error) {
  //     return false;
  //   }
  // };
  // const handleCommission = async () => {
  //   try {
  //     const { data } = await queryCommission();
  //     data.map((item, index) => {
  //       item.label = item.name;
  //       item.value = item.id;
  //     });
  //   } catch (error) {
  //     return false;
  //   }
  // };
  const findNode = (row, storeList) => {
    let list = [];
    storeList.forEach((obj) => {
      if (obj.id === row.storeId) {
        obj.commission = row.commission;
      } else {
        if (obj.children && obj.children.length > 0) {
          let children = findNode(row, obj.children);
          obj.children = children;
        }
      }
      list.push(obj);
    });
    return list;
  };
  const handleGetPostion = (params) => {
    queryPositionMessage(params).then((res) => {
      if (res.data) {
        const {
          data: { positionStoreList },
        } = res;
        setStoreArr(positionStoreList);
      }
    });
  };
  const handleCommissionList = (payload) => {
    setCommissionValue(payload);
  };
  useEffect(() => {
    handleGetDepartment();
    handleGetPosition();
    handleGetQueryRole();
    // handleCommission();
  }, []);

  const TreeOnChange = (value) => {
    handleTreeValue(value);
  };

  const PositionOnChange = (value) => {
    if (value){
      setPositionValue(value);
      queryGetStore(value).then((res) => {
        if (res.code === 0 && res.data) {
          const {
            data: { positionStoreList },
          } = res;
          setStoreArr(positionStoreList);
        }
      });
    }
  };
  const editColumns = [
    {
      title: '工号',
      dataIndex: 'number',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            pattern: new RegExp(/^[1-9]\d*$/, 'g'),
            message: '请输入数字!',
          },
        ],
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input disabled={createEditModalVisible} placeholder={'请输入工号'} />;
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '姓名为必填项',
          },
        ],
      },
    },

    {
      title: '手机号',
      dataIndex: 'mobile',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '手机号为必填项',
          },
        ],
      },
    },
    {
      title: '是否是管理员',
      dataIndex: 'isAdmin',
      valueType: 'text',
      hideInTable: false,
      valueEnum: {
        false: {
          text: '否',
          status: 'Default',
        },
        true: {
          text: '是',
          status: 'Success',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择是否是管理员">
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '是否是管理员为必选项',
          },
        ],
      },
    },

    {
      title: '职位',
      dataIndex: 'positionId',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} className="formItem_div">
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={positionValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择职位"
              allowClear
              treeDataSimpleMode
              treeData={positionIdArr}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={PositionOnChange}
            />
          </FormItem>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '职位为必选项',
          },
        ],
      },
    },

    {
      title: '部门',
      dataIndex: 'deptId',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} className="formItem_div">
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择部门"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '部门为必选项',
          },
        ],
      },
    },

    {
      title: '角色',
      dataIndex: 'roleId',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择角色">
            {roleIdArr.map((item_, index) => {
              return (
                <Option key={index} value={item_.id}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '角色为必选项',
          },
        ],
      },
    },
    {
      title: '是否禁用',
      dataIndex: 'status',
      valueType: 'text',
      hideInTable: false,
      valueEnum: {
        0: {
          text: '否',
          status: 'Default',
        },
        1: {
          text: '是',
          status: 'Success',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否禁用">
            <Option value={1}>是</Option>
            <Option value={0}>否</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '是否禁用为必选项',
          },
        ],
      },
    },
    // {
    //   title: '提成选项',
    //   dataIndex: 'commissionList',
    //   hideInTable: true,
    //   hideInSearch: true,
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     return (
    //       <Checkbox.Group
    //         options={commission}
    //         onChange={handleCommissionList}
    //         value={commissionValue}
    //       />
    //     );
    //   },
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: commissionState,
    //         message: '提成选项为必选项',
    //       },
    //     ],
    //   },
    // },
    // {
    //   title: '店铺列表',
    //   dataIndex: 'positionStoreList',
    //   hideInSearch: true,
    //   hideInTable: true,
    //   renderFormItem: (item, { defaultRender, ...rest }, form) => {
    //     return (
    //       <EditStore
    //         dataSource={storeArr}
    //         changeChildren={handleChildren}
    //         handleChildren={handleChildren}
    //       />
    //     );
    //   },
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: sotreState,
    //         message: '店铺为必选项',
    //       },
    //     ],
    //   },
    // },
  ];
  const columns = [
    {
      title: '工号',
      dataIndex: 'number',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      formItemProps: {
        rules: [
          {
            required: new RegExp(/^[1-9]\d*$/, 'g'),
            message: '工号只能是数字',
          },
          {
            required: true,
            message: '工号为必填项',
          },
        ],
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '姓名为必填项',
          },
        ],
      },
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '手机号为必填项',
          },
        ],
      },
    },
    {
      title: '是否是管理员',
      dataIndex: 'isAdmin',
      valueType: 'text',
      hideInTable: false,
      valueEnum: {
        false: {
          text: '否',
          status: 'Default',
        },
        true: {
          text: '是',
          status: 'Success',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择是否是管理员">
            <Option value={true}>是</Option>
            <Option value={false}>否</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '所属店面为必选项',
          },
        ],
      },
    },
    // {
    //   title: '所属店面',
    //   dataIndex: 'storeName',
    //   valueType: 'text',
    //   hideInSearch: true,
    //   formItemProps: {
    //     rules: [
    //       {
    //         required: true,
    //         message: '所属店面为必选项',
    //       },
    //     ],
    //   },
    // },
    {
      title: '职位',
      dataIndex: 'positionName',
      valueType: 'text',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '职位为必选项',
          },
        ],
      },
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '部门',
      dataIndex: 'deptId',
      // hideInTable: true,
      hideInSearch: true,
      render: (_, payload) => {
        return (
          <>
            <span>{payload.deptName}</span>
          </>
        );
      },
    },
    {
      title: '是否禁用',
      dataIndex: 'status',
      valueType: 'text',
      hideInTable: false,
      valueEnum: {
        0: {
          text: '否',
          status: 'Default',
        },
        1: {
          text: '是',
          status: 'Success',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="是否禁用">
            <Option value={1}>是</Option>
            <Option value={0}>否</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '是否禁用为必选项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Access accessKey={"@updateUser"}>
            <a
              onClick={async () => {
                PositionOnChange(record.positionId);
                setFormValues(record);
                handleEditModalVisible(true);
                setSotreState(false);
                setCommissionState(false);
                handleGetPostion(record.positionId);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@deleteUser"}>
            <Popconfirm
              title="确定删除用户吗?"
              onConfirm={() => handleRemove(record, actionRef)}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>

        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        scroll={{ x: 1200 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@newUser"}>
            <Button
              type="primary"
              onClick={() => {
                handleModalVisible(true);
                setStoreArr([]);
                setCommissionValue([]);
                setSotreState(false);
                setCommissionState(false);
                handleGetQueryRole();

                // setStoreArr(recordRef.current);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          </Access>
          ,
        ]}
        // options={false}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list || [];
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
        title="修改用户"
        width={900}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            // value.employeeStoreList = JSON.parse(JSON.stringify(storeArr));
            // const reArray = JSON.parse(JSON.stringify(commissionValue));
            // let arr = [];
            // reArray.map((item) => {
            //   arr.push({ id: item });
            // });
            value.id = FormValues.id;
            // value.commissionList = arr;
            if (value) {
              const success = await handleEdit(value, actionRef);
              if (success) {
                handleEditModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              } else {
                message.error(success.message);
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: FormValues,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 7 },
            wrapperCol: { span: 24 },
          }}
          columns={editColumns}
        />
      </CreateForm>
      <CreateForm
        title="添加用户"
        width={900}
        onCancel={() => {
          handleModalVisible(false);
          setCommissionValue([]);
        }}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            // value.employeeStoreList = JSON.parse(JSON.stringify(storeArr));
            if (value) {
              const success = await handleAdd(value, actionRef);
              if (success) {
                handleModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }
            // if (commissionValue.length === 0) {
            //   setCommissionState(true);
            // } else {
            //   let arr = JSON.parse(JSON.stringify(commissionValue));
            //   let newArr = [];
            //   arr.map((item, index) => {
            //     var list = {};
            //     list.id = item;
            //     return newArr.push(list);
            //   });
            //   value.commissionList = newArr;
            // }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 7 },
            wrapperCol: { span: 20 },
          }}
          columns={editColumns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
